
<template>
  <div class="layout">

    <!--回到顶部-->
    <BackTop :height="300" :bottom="100">
      <div class="top"></div>
    </BackTop>
    <!--回到顶部-->
    <Layout>
      <!--导航栏-->
      <Affix :style="{zIndex: '999'}">
        <Header :style="{position: 'fixed', width: '100%'}">
          <i-menu mode="horizontal" theme="light" :active-name="$store.state.index" @on-select="select">
            <div class="layout-logo">
            </div>
            <div class="layout-nav">
              <Row type="flex" justify="end">
                <i-col  :xs="2" :sm="4" :md="6" :lg="4">
                  <div>
                    <MenuItem name="1">
                      <Avatar src="http://dd.ddandang.top/blog/images/index.png" size="23" />
                      首页
                    </MenuItem>
                  </div>
                </i-col>
                <i-col :xs="2" :sm="4" :md="6" :lg="4" v-if="$store.state.user.position">
                  <div>
                    <MenuItem name="2" to="/classification">
                      <Avatar src="http://dd.ddandang.top/blog/images/classification.png" size="23" />
                      分类
                    </MenuItem>
                  </div>
                </i-col>
                <i-col :xs="2" :sm="4" :md="6" :lg="4">
                  <div>
                    <MenuItem name="3">
                      <Avatar src="http://dd.ddandang.top/blog/images/journal.png" size="23" />
                      日志
                    </MenuItem>
                  </div>
                </i-col>
                <i-col :xs="2" :sm="4" :md="6" :lg="4">
                  <div>
                    <MenuItem name="4">
                      <Avatar src="http://dd.ddandang.top/blog/images/me.png" size="23" />
                      关于Me
                    </MenuItem>
                  </div>
                </i-col>
                <i-col :xs="2" :sm="4" :md="6" :lg="4" v-if="$store.state.user.position">
                  <div>
                    <Submenu name="5" style="z-index: 500">
                      <template slot="title">
                        <Avatar src="http://dd.ddandang.top/blog/images/blog.png" size="23" />
                        博客
                      </template>
                      <MenuItem name="5-1" to="/write">
                        <Avatar src="http://dd.ddandang.top/blog/images/write.png" size="23" />
                        写博客
                      </MenuItem>
                      <MenuItem name="5-2" to="/manage">
                        <Avatar src="http://dd.ddandang.top/blog/images/manage.png" size="23" />
                        文章管理
                      </MenuItem>
                      <MenuItem name="5-3" to="/draft">
                        <Avatar src="http://dd.ddandang.top/blog/images/draft.png" size="23" />
                        草稿箱
                      </MenuItem>
                    </Submenu>
                  </div>
                </i-col>
                <i-col :xs="2" :sm="4" :md="6" :lg="4">
                  <div>
                    <MenuItem v-if="$store.state.user.userId === 0" name="6" to="/login">
                      <Avatar src="http://dd.ddandang.top/blog/images/login.png" size="23" />
                      登录
                    </MenuItem>
                    <Dropdown @on-click="editUserInfo" v-else>
                      <a href="javascript:void(0)">
                        <Avatar :src="$store.state.user.avatar" size="40" />
                        <Icon type="ios-arrow-down"></Icon>
                      </a>
                      <DropdownMenu slot="list">
                        <DropdownItem name="1">{{$store.state.user.nickname}}</DropdownItem>
                        <DropdownItem name="2">信息修改</DropdownItem>
                        <DropdownItem name="3">退出登录</DropdownItem>
                      </DropdownMenu>
                    </Dropdown>
                  </div>
                </i-col>
              </Row>

            </div>
          </i-menu>
        </Header>
      </Affix>
      <!--导航栏-->
      <!--信息编辑-->
      <Drawer
              title="个人信息修改"
              v-model="editInfo"
              width="500"
              :styles="styles"
      >
        <!--编辑头像-->
        <div style="text-align: center">
          <!--头像上传-->
          <Upload
                  ref="upload"
                  :show-upload-list="false"
                  :format="['jpg','jpeg','png']"
                  :max-size="2048"
                  type="drag"
                  :on-success="uploadAvatarSuccess"
                  :on-error="uploadAvatarError"
                  :data="{
                      username: $store.state.user.username
                    }"
                  :action="uploadAvatarUrl"
                  style="display: inline-block;width:200px;">
            <Avatar :src="$store.state.user.avatar" size="200"></Avatar>
          </Upload>
        </div>
        <div class="editNickname">
          <i-input @on-search="changeNickname" search enter-button="修改" type="text" v-model="nickname"  number placeholder="请输入昵称。。"></i-input>
        </div>

        <div class="changePassword">
          <Form ref="passwordInfo" :model="passwordInfo" :rules="ruleCustom" :label-width="80">
            <FormItem label="原始密码" prop="oldPassword">
              <i-input type="password" v-model="passwordInfo.oldPassword"></i-input>
            </FormItem>
            <FormItem label="新密码" prop="password">
              <i-input type="password" v-model="passwordInfo.password"></i-input>
            </FormItem>
            <FormItem label="确认密码" prop="passwordCheck">
              <i-input type="password" v-model="passwordInfo.passwordCheck"></i-input>
            </FormItem>
            <FormItem style="margin-top: 40px">
              <Button type="primary" @click="handleSubmit('passwordInfo')">修改</Button>
              <Button @click="handleReset('passwordInfo')" style="margin-left: 8px">取消</Button>
            </FormItem>
          </Form>
        </div>
      </Drawer>

      <Content :style="{margin: '88px 20px 0', background: '#fff', minHeight: '800px'}">
        <slot></slot>
      </Content>
      <Footer class="layout-footer-center">&copy;2020  D.</Footer>
    </Layout>
  </div>
</template>


<script>
  import {uploadUserAvatar, updateNickname, changePassword, logOut} from "@/network/user";

  export default {
    name: "NavigationBar",
    data() {
      const validateOldPassword = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入原始密码！'));
        } else if(value.length < 6) {
          callback(new Error('密码不少于6位数！'));
        }else {
          if (this.passwordInfo.password !== '') {
            // 判断原始密码和新密码是否相同
            this.$refs.passwordInfo.validateField('password');
          }
          callback();
        }
      };
      const validatePassword = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入新密码！'));
        } else if(value.length < 6) {
          callback(new Error('密码不少于6位数！'));
        }else if (value === this.passwordInfo.oldPassword) {
          callback(new Error('新密码不能与原始密码相同！'));
        }else {
          if (this.passwordInfo.passwordCheck !== '') {
            // 对第二个密码框单独验证
            this.$refs.passwordInfo.validateField('passwordCheck');
          }
          callback();
        }
      };
      const validatePasswordCheck = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入确认密码！'));
        } else if(value.length < 6) {
          callback(new Error('密码不少于6位数！'));
        } else if (value !== this.passwordInfo.password) {
          callback(new Error('两次输入的新密码不相同！'));
        } else {
          callback();
        }
      }

      return {
        //上传地址
        uploadAvatarUrl: '',
        index: '3',
        editInfo: false,
        styles: {
          height: 'calc(100% - 55px)',
          overflow: 'auto',
          paddingBottom: '53px',
          position: 'static'
        },
        nickname: '',
        name: '',
        //改密码
        passwordInfo: {
          oldPassword: '',
          password: '',
          passwordCheck: ''
        },
        ruleCustom: {
          oldPassword: [
            { validator: validateOldPassword, trigger: 'blur' }
          ],
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          passwordCheck: [
            { validator: validatePasswordCheck, trigger: 'blur' }
          ]
        }
      }
    },
    mounted() {
      this.uploadAvatarUrl = uploadUserAvatar;
    },
    methods: {
      select(name) {
        const token = this.$store.state.token;
        if (token === '') {
          this.$Message.error('请先登录！');
          this.$store.commit('changeIndex',1);
          return;
        }
        this.$store.commit('changeIndex',name);
        if (name === '1') {
          this.$router.push({ path: '/' })
          return;
        }
        if (name === '3') {
          this.$router.push({ path: '/journal' })
          return;
        }
        if (name === '4') {
          this.$router.push({ path: '/aboutMe' })
          return;
        }
      },
      editUserInfo(name) {
        if(name === '2'){
          this.nickname = this.$store.state.user.nickname;
          this.editInfo = !this.editInfo
        }else if(name === '3') {
          //点击了退出登录
          this.logOut();
        }
      },
      //上传头像成功
      uploadAvatarSuccess(response) {
        let url = response.data.url
        //将本地的信息进行修改
        this.$store.commit('setAvatar', url)
        //将用户信息放到本地
        window.localStorage.setItem("user", JSON.stringify(this.$store.state.user));
      },
      //上传头像成功
      uploadAvatarError() {
        this.$Message.error('接口错误！上传失败！')
      },
      //修改昵称
      changeNickname() {
        let nickname = this.nickname;

        if(nickname === '') {
          this.$Message.error({
            background: true,
            content: '昵称不能为空！'
          })
          return;
        }
        if(nickname.length > 7) {
          this.$Message.error({
            background: true,
            content: '昵称不能大于7个字符！'
          })
          return;
        }
        this.updateNickname(nickname);
      },
      //更新用户昵称
      updateNickname(nickname) {
        updateNickname(nickname, this.$store.state.user.username).then(res => {
          if (res.code === 2000) {
            this.$store.commit("setNickname", nickname);
            window.localStorage.setItem("user", JSON.stringify(this.$store.state.user));

            this.$Message.success({
              background: true,
              content: '修改成功！'
            })
            return;
          }
          this.$Message.error({
            background: true,
            content: '修改失败！'
          })
        })
      },
      handleSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.changePassword();
          } else {
            this.$Message.error('请正确填写信息!');
          }
        })
      },
      handleReset (name) {
        this.$refs[name].resetFields();
      },
      //修改密码
      changePassword() {
        changePassword(this.passwordInfo.oldPassword, this.passwordInfo.password, this.$store.state.user.username)
        .then(res => {
          if(res.code === 2000) {
            this.$Message.success({
              background: true,
              content: '修改密码成功！'
            })
            return;
          }
          if(res.code === 4000) {
            this.$Message.error({
              background: true,
              content: '原始密码错误！'
            })
            return;
          }
          this.$Message.error({
            background: true,
            content: '修改密码失败！'
          })
        })
      },
      //退出登录
      logOut() {
        logOut(this.$store.state.user.userId).then(res => {
          if(res.code === 2000) {
            //删除Vuex数据
            this.$store.commit('resetUser');
          }
        })
      }

    }
  }
</script>

<style scoped>
  .ivu-layout-header {
    background-color: #fff;
  }
  .layout{
    border: 1px solid #d7dde4;
    background: #f5f7f9;
    position: relative;
    border-radius: 4px;
    overflow: hidden;
  }
  .layout-logo{
    text-align: center;
    background: url("http://dd.ddandang.top/blog/images/logo.png") no-repeat;
    background-size: cover;
    width: 200px;
    height: 45px;
    border-radius: 3px;
    float: left;
    position: relative;
    top: 10px;
    left: 20px;
  }
  .tags-item {
    text-align: center;
    margin-top: 15px;
  }
  .tags-item :hover {
    cursor: default;
  }
  .layout-nav{
    float: right;
    width: 70%;
    margin: 0 20px 0 auto;
  }
  .layout-footer-center{
    text-align: center;
  }
  .top {
    width: 80px;
    height: 72px;
    background: url("http://dd.ddandang.top/blog/images/up.png") no-repeat;
    background-size: cover;
  }
  .item {
    text-align: center;
  }
  .editNickname {
    margin-top: 20px;
    text-align: center;
  }
  .changePassword {
    margin-top: 50px;
  }
</style>
